package com.whut.mobilesafe.activity;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.IPackageStatsObserver;
import android.content.pm.PackageManager;
import android.content.pm.PackageStats;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.RemoteException;
import android.os.SystemClock;
import android.text.format.Formatter;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.whut.mobilesafe.R;
import com.whut.mobilesafe.domain.CacheInfo;

import java.lang.reflect.Method;
import java.util.List;
import java.util.Random;

/**
 * 作    者：yubo.xiaoyubo
 * 时    间：2016/1/2  18:22.
 * 版    本：1.0
 * 描    述：
 */
public class CacheActivity extends Activity {

    private static final int STATE_UPDATE_INFO = 1;
    private static final int STATE_FINISH_UPDATE = 2;
    private static final int STATE_FIND_CACHE = 3;

    private ImageView ivIcon;
    private TextView tvName;
    private TextView tvSize;
    private ImageButton ibClear;

    private List<ApplicationInfo> mInstalledApplications;
    private LinearLayout llContainer;
    private ProgressBar pbLoading;
    private TextView tvTitle;

    private Handler mHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case STATE_UPDATE_INFO:
                    String packageName = (String) msg.obj;
                    tvTitle.setText("正在扫描：" + packageName);
                    break;

                case STATE_FINISH_UPDATE:
                    tvTitle.setText("扫描结束");
                    break;

                case STATE_FIND_CACHE:
                    final CacheInfo info = (CacheInfo) msg.obj;
                    View view = View.inflate(getApplicationContext(), R.layout.list_item_cache, null);

                    ivIcon = (ImageView) view.findViewById(R.id.iv_icon);
                    tvName = (TextView)  view.findViewById(R.id.tv_name);
                    tvSize = (TextView)  view.findViewById(R.id.tv_size);
                    ibClear = (ImageButton)  view.findViewById(R.id.ib_clear);

                    tvName.setText(info.name);
                    ivIcon.setImageDrawable(info.icon);
                    tvSize.setText(Formatter.formatFileSize(getApplicationContext(),info.size));

                    ibClear.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Intent intent = new Intent();
                            intent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
                            intent.setData(Uri.parse("package:" +info.name));
                            startActivity(intent);
                        }
                    });
                    llContainer.addView(view,0);
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_cache);

        llContainer = (LinearLayout) findViewById(R.id.ll_container);
        pbLoading = (ProgressBar) findViewById(R.id.pb_loading);
        tvTitle = (TextView) findViewById(R.id.tv_title);

        initData();
    }

    private void initData() {
        new Thread() {

            @Override
            public void run() {
                PackageManager packageManager = getPackageManager();
                mInstalledApplications = packageManager.getInstalledApplications(PackageManager.GET_UNINSTALLED_PACKAGES);
                pbLoading.setMax(mInstalledApplications.size());
                int progress = 0;
                for (ApplicationInfo info : mInstalledApplications) {
                    //获取缓存大小
                    try {
                        Method method = packageManager.getClass().getMethod(
                                "getPackageSizeInfo", String.class,
                                IPackageStatsObserver.class);
                        method.invoke(packageManager, info.packageName, new MyObserver());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                    progress++;
                    pbLoading.setProgress(progress);

                    //加载安装包的应用信息

                    Message msg = Message.obtain();
                    msg.what = STATE_UPDATE_INFO;
                    msg.obj = info.packageName;
                    mHandler.sendMessage(msg);
                    SystemClock.sleep(200 + new Random().nextInt(100));
                }

                mHandler.sendEmptyMessage(STATE_FINISH_UPDATE);

            }
        }.start();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }


    class MyObserver extends IPackageStatsObserver.Stub {

        @Override
        public void onGetStatsCompleted(PackageStats pStats, boolean succeeded) throws RemoteException {
            CacheInfo info = new CacheInfo();

            PackageManager packageManager = getPackageManager();
            try {
                ApplicationInfo applicationInfo = packageManager.getApplicationInfo(pStats.packageName, PackageManager.GET_UNINSTALLED_PACKAGES);
                String name = applicationInfo.loadLabel(packageManager).toString();
                Drawable icon = applicationInfo.loadIcon(packageManager);


                long cacheSize = pStats.cacheSize;
                if (cacheSize > 0) {


                    info.name = pStats.packageName;
                    info.icon = icon;
                    info.size = cacheSize;

                    Message msg = Message.obtain();
                    msg.obj = info;
                    msg.what = STATE_FIND_CACHE;
                    mHandler.sendMessage(msg);
                }

            } catch (PackageManager.NameNotFoundException e) {
                e.printStackTrace();
            }

        }
    }

    public void clearCache(View view){

    }
}
